# -*- coding: utf-8 -*-
import csv
import sys
import random
import sqlite3
def createCsvRoot(reader1,reader2,writer):
	cx = sqlite3.connect("test.db")
	cu = cx.cursor()
	cu.execute("DROP TABLE IF EXISTS lineloss")
	cu.execute("create table lineloss (name string primary key,parent string,inVol string,outVol string)")
	for line in reader1:
		if not(line[0]=="name"):
			if(line[0]=="500kv@0"):
				cu.execute("INSERT INTO lineloss (name, parent) VALUES('%s','%s')"%(line[0],line[0]))				
			children=line[1].split()
			for child in children:
				cu.execute("INSERT INTO lineloss (name, parent) VALUES('%s','%s')"%(child,line[0]))
	cx.commit()
	for line in reader2:
		if not(line[0]=="name"):
			cu.execute("update lineloss set inVol='%s',outVol='%s' where name = '%s'"%(line[1],line[2],line[0]))
	cx.commit()
	cu.execute("select * from lineloss")
	res = cu.fetchall()	
	for line in res:
		if(line[2]==0):
			writer.write(line[0]+','+line[1]+','+str(line[2])+','+str(line[3])+'\n')
if __name__ == '__main__':
	print "create in out csv"
	if len(sys.argv)==3:#第一个参数是输入文件，第二个参数是输出文件
		with open(sys.argv[1], 'rb') as csvfile:
			reader = csv.reader(csvfile)			
			with open(sys.argv[2],'rb') as csvfile2:
				reader2 = csv.reader(csvfile2)
				with open(sys.argv[3],'wb+') as csvfile3:
					createCsvRoot(reader,reader2,csvfile3)		
	else:		
		with open('dataForStorm.csv', 'rb') as csvfile:	
			reader = csv.reader(csvfile)				
			with open('inoutForStorm.csv','rb') as csvfile2:
				reader2 = csv.reader(csvfile2)
				with open('forHadoop.csv','wb+') as csvfile3:					
					createCsvRoot(reader,reader2,csvfile3)